import { ProForm, ProFormInstance } from '@/components/Pro';
import { parseArray } from '@/pages/Statistics/Battery/utils';
import { TreeNode } from '@/pages/Statistics/PowerGeneration/help';
import { getDeviceCascader } from '@/utils/formatterTree';
import { useIntl } from '@umijs/max';
import { Button, DatePicker, message, Space, TreeSelect } from 'antd';
import dayjs from 'dayjs';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';

type IProps = {
  dateType: string;
  submitForm: (data: any) => void;
};

const ChartForm: React.FC<IProps> = (props) => {
  const intl = useIntl();

  const formRef = useRef<ProFormInstance>();
  const { dateType, submitForm } = props;
  const [selectDate, setSelectDate] = useState(
    dateType === 'date' ? dayjs() : dateType === 'month' ? dayjs() : dayjs(),
  );
  const [treeData, setTreeData] = useState([]);

  const [code, setCode] = useState(null);
  const [cascaderVal, setCascaderVal] = useState();
  const [areaFlag, setAreaFlag] = useState(false);
  const selectedType = useRef(null);

  /**
   * 获得禁用列表
   * @param Nodes
   */
  const setDisabled = (Nodes: TreeNode[]): TreeNode[] => {
    return Nodes.map((node) => {
      const newNode: TreeNode = {
        ...node,
        disabled: selectedType.current === null ? false : node.nodeType !== selectedType.current,
      };
      if (newNode.subDevices) {
        newNode.subDevices = setDisabled(newNode.subDevices);
      }
      return newNode;
    });
  };
  const getBatterStack = () => {
    getDeviceCascader(false, undefined, ['BMS']).then((res) => {
      setCascaderVal(res[0].uniqueId);
      setCode(res[0].stationCode);
      selectedType.current = 'ROOT';
      setTreeData(setDisabled([res[0]]));
      submitForm({
        code: res[0].stationCode,
        date: selectDate,
        areaFlag: false,
      });
    });
  };

  useEffect(() => {
    setSelectDate(dateType === 'date' ? dayjs() : dateType === 'month' ? dayjs() : dayjs());
  }, [dateType]);

  useEffect(() => {
    getBatterStack();
  }, []);

  return (
    <div style={{ paddingLeft: '60px' }}>
      <ProForm formRef={formRef} layout={'inline'} submitter={false}>
        <ProForm.Item
          label={intl.formatMessage({ id: 'statistics.income.select' })}
          initialValue={dateType === 'date' ? dayjs() : dateType === 'month' ? dayjs() : dayjs()}
        >
          <DatePicker
            allowClear={false}
            disabledDate={(current) => {
              return current && current > moment().endOf('day');
            }}
            value={selectDate}
            picker={dateType}
            onChange={(value) => {
              setSelectDate(value);
            }}
          ></DatePicker>
        </ProForm.Item>
        <ProForm.Item label={intl.formatMessage({ id: 'statistics.work.dimensions' })}>
          <TreeSelect
            style={{ width: '200px' }}
            maxTagCount={'responsive'}
            multiple={true}
            value={cascaderVal}
            maxCount={100}
            fieldNames={{
              label: 'deviceName',
              value: 'uniqueId',
              children: 'subDevices',
            }}
            treeData={treeData}
            onSelect={(...args) => {
              let selectOptions = args[1];
              if (selectedType.current === null && selectOptions?.nodeType) {
                selectedType.current = selectOptions?.nodeType;
              }
              setTreeData(setDisabled([treeData[0]]));
            }}
            onChange={(...args) => {
              setCascaderVal(args[0]);
              let selectedOptions = args[1];
              if (!selectedOptions.length) {
                //清除后不再做相应限制
                selectedType.current = null;
                setTreeData(setDisabled([treeData[0]]));
              }
              let hasAreaNode: boolean = false;
              const ans = parseArray(args[0]);
              if (ans.nodeType.length) {
                hasAreaNode = ans.nodeType.some((item: string) => {
                  return item === 'AREA';
                });
              }
              setAreaFlag(hasAreaNode);
              if (!hasAreaNode) {
                setCode(ans.id);
              } else {
                setCode(ans.id.join(','));
              }
            }}
          ></TreeSelect>
        </ProForm.Item>

        <ProForm.Item>
          <Space>
            <Button
              type={'primary'}
              onClick={() => {
                if (!code || !code?.length) {
                  message.warning('请选择统计维度');
                  return false;
                }
                submitForm({
                  code: code,
                  date: selectDate,
                  areaFlag: areaFlag,
                });
              }}
            >
              {intl.formatMessage({ id: 'global.search' })}
            </Button>
            <Button
              onClick={() => {
                selectedType.current = 'ROOT';
                setTreeData(setDisabled([treeData[0]]));
                setSelectDate(dayjs());
                setCascaderVal(treeData[0].uniqueId);
                setCode(treeData[0].stationCode);
                submitForm({
                  date: dayjs(),
                  stationCode: '',
                  code: treeData[0].stationCode,
                  areaFlag: false,
                });
              }}
            >
              {intl.formatMessage({ id: 'global.reset' })}
            </Button>
          </Space>
        </ProForm.Item>
      </ProForm>
    </div>
  );
};

export default ChartForm;
